package com.lanmaoly.web.server.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanmaoly.web.server.dao.TbAddressMapper;
import com.lanmaoly.web.server.entity.PageResult;
import com.lanmaoly.web.server.pojo.TbAddress;
import com.lanmaoly.web.server.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 服务实现层
 *
 * @author Administrator
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private TbAddressMapper addressMapper;

    /**
     * 查询全部
     */
    @Override
    public List<TbAddress> findAll() {
        return addressMapper.findAll();
    }

    /**
     * 按分页查询
     */
    @Override
    public PageResult findPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<TbAddress> page = addressMapper.findPage(new TbAddress());
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 增加
     */
    @Override
    public void add(TbAddress address) {
        addressMapper.insertSelective(address);
    }


    /**
     * 修改
     */
    @Override
    public void update(TbAddress address) {
        addressMapper.updateByPrimaryKeySelective(address);
    }

    /**
     * 根据ID获取实体
     *
     * @param id
     * @return
     */
    @Override
    public TbAddress findOne(Long id) {
        return addressMapper.selectByPrimaryKey(id);
    }

    /**
     * 批量删除
     */
    @Override
    public void delete(Long[] ids) {
        for (Long id : ids) {
            addressMapper.deleteByPrimaryKey(id);
        }
    }


    @Override
    public PageResult findPage(TbAddress address, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<TbAddress> page = addressMapper.findPage(address);
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public List<TbAddress> findListByUserId(String userId) {
        return addressMapper.findListByUserId(userId);
    }

    @Override
    public void setDefault(Long id) {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        addressMapper.updateDefaultIsNot(name);
        TbAddress tbAddress = new TbAddress();
        tbAddress.setId(id);
        tbAddress.setIsDefault("1");
        addressMapper.updateByPrimaryKeySelective(tbAddress);
    }

}
